package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constants.MQConstants.Exchange;
import com.leyou.common.constants.MQConstants.RoutingKey;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.pojo.*;
import org.springframework.amqp.core.AmqpTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsService {


    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    AmqpTemplate amqpTemplate;


    public PageResult<SpuDTO> querySpuByPage(Integer page, Integer rows, Boolean saleable, Boolean key) {
        //1.分页
        PageHelper.startPage(page, rows);
        //2.过滤
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //2.1搜索过滤条件查询
        if (!StringUtils.isEmpty(key)) {
            criteria.andLike("name", "%" + key + "%");
        }
        //2.2上下架过滤查询
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        // 2.3 默认按时间排序
        example.setOrderByClause("update_time DESC");
        //3查询结果
        List<Spu> spuList = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(spuList)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        //4封装分页结果
        PageInfo<Spu> pageInfo = new PageInfo<>(spuList);
        //DTO转换
        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(spuList, SpuDTO.class);
        // 5 处理分类名称和品牌名称
        handleCategoryAndBrandName(spuDTOS);
        return new PageResult<>(pageInfo.getTotal(), spuDTOS);
    }

    //获取到每一个spu中商品分类(类目),用/间隔开来而已
    private void handleCategoryAndBrandName(List<SpuDTO> list) {
        for (SpuDTO spu : list) {
            // 查询分类
            String categoryName = categoryService.queryCategoryByIds(spu.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName).collect(Collectors.joining("/"));
            spu.setCategoryName(categoryName);
            // 查询品牌
            BrandDTO brand = brandService.queryById(spu.getBrandId());
            spu.setBrandName(brand.getName());
        }
    }

    public void save(SpuDTO spuDTO) {
        //取出spu信息
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(false);
        int count = spuMapper.insertSelective(spu);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }

        //保存spudetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        spuDetailDTO.setSpuId(spu.getId());
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
        count = detailMapper.insert(spuDetail);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
        //准备sku数据
        List<SkuDTO> skuDTOS = spuDTO.getSkus();
        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOS) {
            skuDTO.setSpuId(spu.getId());
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setCreateTime(new Date());
            sku.setUpdateTime(new Date());
            skuList.add(sku);
        }
        //保存sku
        count = skuMapper.insertList(skuList);
        if (count != 1) {
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }

    public void updateSaleable(Long id, Boolean saleable) {
        try {
            Spu spu = new Spu();
            spu.setId(id);
            spu.setSaleable(saleable);
            //修改spu 一定要用Selective
            int count = spuMapper.updateByPrimaryKeySelective(spu);
            if (count != 1) {
                throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
            }
            //更新sku
            Sku sku = new Sku();
            sku.setEnable(saleable);
            Example example = new Example(Sku.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("spuId", id);
            count = skuMapper.updateByExampleSelective(sku, example);
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

        //向交换机发送消息      本身就是boolean值了
        String routingKey = saleable ? RoutingKey.ITEM_UP_KEY:RoutingKey.ITEM_DOWN_KEY;
        //使用amqp发送消息           交换机  key  内容
        amqpTemplate.convertAndSend(Exchange.ITEM_EXCHANGE_NAME,routingKey,id);
    }

    public SpuDetailDTO querySpuDetailById(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> skuList = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }

    public void updateGoods(SpuDTO spuDTO) {

        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        spu.setSaleable(false);//下架
        spuMapper.updateByPrimaryKey(spu);//同时还修改了商品id,品牌id
        //修改spudetail
        SpuDetailDTO spuDetailDTO = spuDTO.getSpuDetail();
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDetailDTO, SpuDetail.class);
//        spuDetail.setSpuId(spu.getId());前端请求时已经封装上了
        detailMapper.updateByPrimaryKey(spuDetail);
        //根据spuid删除之前的sku
        Sku sku = new Sku();
        sku.setSpuId(spu.getId());
        skuMapper.delete(sku);//会删除所有spuid为xxx的sku对象

        //添加sku
        List<SkuDTO> skusDTO = spuDTO.getSkus();
        List<Sku> skus = BeanHelper.copyWithCollection(skusDTO, Sku.class);
        skus.forEach(newSku -> {
            newSku.setSpuId(spu.getId());
            newSku.setCreateTime(new Date());
            newSku.setUpdateTime(new Date());
        });
        skuMapper.insertList(skus);
    }

    public SpuDTO querySpuById(Long id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        //查询该spu下的sku和spuDetail
        spuDTO.setSkus(querySkuBySpuId(id));
        spuDTO.setSpuDetail(querySpuDetailById(id));
        return spuDTO;
    }

    public BrandDTO queryBrandByid(Long id) {
        return brandService.queryById(id);
    }

    public List<SkuDTO> querySkuListByIds(List<Long> ids) {
        // 查询sku
        List<Sku> skuList = skuMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skuList, SkuDTO.class);
    }
}
